package cn.com.ajava.tool;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

/**
 * Properties util tool
 * @author zengfantian
 * @date 2011-03-01
 * @version 1.0
 */
@SuppressWarnings("serial")  
public final class  PropertiesTool extends Properties{

	private static String filePath ;
	private static Properties property = new Properties(); 
	
	@SuppressWarnings("unused")
	private PropertiesTool(){
		readProperties();
	}
	
	/**
	 * load the property
	 */
	private static void readProperties(){ 
		try { 
			InputStream  is = new FileInputStream(filePath);
        	property.load(is); 
        	is.close();
        } catch (Exception e) { 
            e.printStackTrace(); 
        }
    } 

	/**
	 * set property's location
	 * @param name filePath
	 */
	public static void setFilePath(String name) {
		filePath = name;
	}
	/**
	 * get the Property of Property file where 
	 * locating at giving the filePath 
	 * @param filePath  filePath
	 * @param key key
	 * @return String value
	 * 
	 */
	public static final String getValueFromProperties(String filePath,String key)
	{
		String value = null;
		try 
		{
			setFilePath(filePath);
			readProperties();
			if(property.containsKey(key))
			{
				value = property.getProperty(key);
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return value;
	}
	/**
	 * get the Property of Property <br>
	 * but you should set PropertiesTool's fileName before using it .<br>
	 * For example: <br>
	 * <p><blockquote><pre>
     * PropertiesTool.setFileName("config.properties");<br>
	 * String host = PropertiesTool.getValueFromProperties("host")
     * </pre></blockquote><p>
	 * @param key  key
	 * @return String value
	 */
	public static final String getValueFromProperties(String key)
	{
		String value = null;
		try {
			readProperties();
			if(property.containsKey(key))
			{
				value = property.getProperty(key);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return value;
	}
	
	
	/**
	 * update Properties Value 
	 * @param filePath filePath
	 * @param key key
	 * @param value value
	 */
	public static final void updatePropertiesValue(String filePath, String key,String value) {
		Properties props = new Properties();
		try {
			InputStream fis = new FileInputStream(filePath);
			props.load(fis);
			fis.close();
			
			OutputStream fos = new FileOutputStream(filePath);
			props.setProperty(key, value);
			props.store(fos, "");
			fos.close();
		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}

	}
	
}
